/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "EraseConfigSetting.h"
#include <QFile>
#include <QDomDocument>
#include "BurnToolCommon/Global.h"

namespace BurnDlg {

namespace {
    const int CHECK_BOX_NUMBER_4 = 4;
}

EraseConfigSetting::EraseConfigSetting(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::EarseConfigSetting()),
      cbEraseConfig(0)
{
    this->setWindowFlags(this->windowFlags() & ~static_cast<int>(Qt::WindowMinMaxButtonsHint));
    ui->setupUi(this);
    ReadMultipleXML();
    InitUi();
    connect(ui->pbOk, &QPushButton::clicked, this, &EraseConfigSetting::SlotBnClickedOK);
}

EraseConfigSetting::~EraseConfigSetting()
{
}

void EraseConfigSetting::ReadMultipleXML()
{
    vecEraseConfig.clear();
    QString path = Global::GetAppConfigPath();
    path += "\\config_" + Global::ChipTypeIdToString(Global::currentChipTypeId);
    path += "\\EraseConfig.xml";
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }
    QDomDocument dom("EraseConfig");
    if (dom.setContent(&file)) {
        QDomNodeList nodeList = dom.elementsByTagName("STRUCT");
        for (int i = 0; i < nodeList.size(); ++i) {
            EraseConfig xmlStruct;
            QDomElement elem = nodeList.at(i).toElement();
            xmlStruct.name = elem.attribute("NAME");
            QDomNodeList typeData = elem.childNodes();
            for (int j = 0; j < typeData.length(); j++) {
                EraseConfig xmlData;
                xmlData.id = typeData.at(j).toElement().attribute("ID").toUInt(); // 16进制读取
                xmlData.name = typeData.at(j).toElement().attribute("NAME");
                vecEraseConfig.push_back(xmlData);
            }
        }
    }
    file.close();
    return;
}

void EraseConfigSetting::InitUi()
{
    for (int i = 0; i < vecEraseConfig.size(); i++) {
        QCheckBox *checkBox = new QCheckBox();
        checkBox->setText(vecEraseConfig[i].name);
        ui->glEraseConfig->addWidget(checkBox, i / CHECK_BOX_NUMBER_4, i % CHECK_BOX_NUMBER_4);
        listCB[vecEraseConfig[i].id] = checkBox;
    }
}

void EraseConfigSetting::SlotBnClickedOK(bool checked)
{
    Q_UNUSED(checked)
    cbEraseConfig = 0;
    for (auto it = listCB.begin(); it != listCB.end(); it++) {
        if (it.value()->checkState() == Qt::Checked) {
            cbEraseConfig = cbEraseConfig | it.key();
        }
    }
    emit SignalSetEraseConfig(cbEraseConfig, vecEraseConfig);
    this->close();
}

}
